﻿using Sgr.Utilities;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Sgr.Serialization
{
    public class UtcDateTimeConverter : JsonConverter<DateTime>
    {
        public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            var value = reader.GetString();

            if (string.IsNullOrEmpty(value))
                throw new JsonException("DateTime 值不能为空或null.");

            return DateTimeHelper.ParseToUtc(value);
        }

        public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
        {
            //if (value.Kind != DateTimeKind.Utc)
            //    throw new JsonException("DateTime 必须是 UTC 时间.");

            var utc = value.Kind switch
            {
                DateTimeKind.Utc => value,
                DateTimeKind.Local => value.ToUniversalTime(),
                _ => UtcDateTimeConverterInternal.HandleUnspecified(value, assumeLocal: false)
            };

            writer.WriteStringValue(utc);
        }
    }
}